<?php
namespace app\h5api\controller;

use app\common\model\ApplySales;
use app\common\model\Exam;
use app\common\model\ExamAnswer;
use app\common\model\Feedback;
use app\common\model\Footprint;
use app\common\model\Collection;
use app\common\model\GrowthLog;
use app\common\model\Order as OrderModel;
use app\common\model\PaperQuestions;
use app\common\model\User;
use app\common\service\Wechat;
use app\h5api\validate\ApplyBeSales;
use think\facade\Config;
use Upload;
use plug\SUtil;

class My extends Base
{
	/**
	 * @route('h5/GetUserAllInfo','get')
	 * 获取用户信息
	 */
    public function GetUserAllInfo()
    {
        $userinfo = $this->GetUserInfo();
        $userModel = new User();
        $userinfo['invite_count'] = $userModel->where('invite_uid','=',$userinfo['user_id'])->count();
        $applyModel = new ApplySales();
        $is_apply = $applyModel->getOne([['user_id','=',$userinfo['user_id']],['status','=',1]]);
        $userinfo['is_apply'] = empty($is_apply)?'false':'true';
        $growthModel = new GrowthLog();
        $userinfo['accumulation'] = $growthModel->where(['user_id'=>$userinfo['user_id'],'cate'=>'+'])->sum('change_value');
        $orderModel = new OrderModel();
        $userinfo['order_count'] = $orderModel->where('order_status','between',[2,4])->where('user_id','in',function($query) use($userinfo){
            $query->table('ddt_user')->where('invite_uid','=',$userinfo['user_id'])->field('user_id');
        })->count();

		if($userinfo['invite_uid'] > 0){
			$invite_name = $userModel->where([
				'user_id' => $userinfo['invite_uid']
			])->value('nick_name');
			$userinfo['invite_name'] = $invite_name;
		}

        $this->result(['data'=>$userinfo],1,'操作成功');
    }

	/**
	 * @route('h5/GetFootprintList','get')
	 * 个人足迹
	 */
	public function GetFootprintList()
	{
		$FootprintModel = new Footprint();
		$page = input('get.page') ? input('get.page') : 1;
		$list = $FootprintModel->GetDateList($this->_userid,$page);

		$this->result($list,1,'操作成功');
	}

	/**
	 * @route('h5/GetCollectionList','get')
	 * 个人收藏
	 */
	public function GetCollectionList()
	{
		$CollectionModel = new Collection();
		$data = $CollectionModel->GetMyCollection($this->_userid, $this->limit);

		$this->result($data,1,'操作成功');
	}

	/**
	 * @route('h5/DelCollections','post')
	 * 批量删除个人收藏
	 */
	public function DelCollections()
	{
		$ids = input('post.ids');
		$CollectionModel = new Collection();
		$res = $CollectionModel->Dels($this->_userid,$ids);
		if(!$res){
			$this->result([],-1,'操作失败');
		}
		$this->result([],1,'操作成功');
	}

	/**
	 * @route('h5/UpdateUserInfo','post')
	 * 修改个人信息
	 */
	public function UpdateUserInfo()
	{
	    $validate = new \app\h5api\validate\User();
        $userModel = new User();
		$data = input('post.');

        $res = $validate->scene('EditUser')->check($data);
        if(!$res){
            $this->result('',-1,$validate->getError());
        }

		$res = $userModel->allowField(['nick_name','real_name','phone'])->save($data, ['user_id' => $this->_userid]);
		if(!$res){
			$this->result([],-1,'操作失败');
		}
		$this->result([],1,'操作成功');
	}

	/**
	 * @route('h5/UpdateAvatar','post')
	 * 修改个人头像
	 */
	public function UpdateAvatar()
	{
		$res = Upload::FileUpload('image','avatar',1024*1024*0.5);
		if(!$res['data']){
			$this->result([],-1,$res['msg']);
		}

		$userModel = new User();

		$res = $userModel->save(['avatar'=> "http://".$_SERVER['HTTP_HOST']."/".$res['data']['file_path']], ['user_id' => $this->_userid]);
		if(!$res){
			$this->result([],-1,'操作失败');
		}
		$this->result([],1,'操作成功');
	}

	/**
	 * @route('h5/Share','post')
	 * 获取分享参数接口
	 */
	public function Share(){
		//将url拼接上分享参数
		$url = input('post.url','https://www.baidu.com');
		$data = input('post.data',[]);
		$data['from_uid'] = $this->_userid;
		$srt = http_build_query($data);
		$share_url = $url.'?'.$srt;

		$jsapiTicket = Wechat::JsapiTicket();
		$nonceStr = SUtil::random(16);
		$timestamp = time();
		//注意！&timestamp会被转义成“xtamp”，将”&”换成”&amp;”
		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
		$signature = sha1($string);

		$return = [
			'signPackage' => [
				'appId'=>config::get('weixin.')['AppID'],
				'nonceStr'=>$nonceStr,
				'timestamp'=>$timestamp,
				'url'=>$url,
				'signature'=>$signature,
				'rawString'=>$string,
			],
			's' => $srt,
			'share_url' => $share_url,
		];
		$this->result($return,1,'操作成功');
	}

    /**
     * @route('h5/UserQrCode','post')
     * 用户获取太阳码
     */
    public function UserQrCode() {
        $url = input('post.url');
        $userinfo = $this->GetUserInfo();
        if(!empty($userinfo['sun_image'])){
            $this->result(['path'=> $userinfo['sun_image']],1,'返回成功');
        }
        $url = parse_url($url)['path'];
//        var_dump($code);die;
        $scene = [
            "from_uid" => $userinfo['user_id'],
        ];
        $wxconf = config::pull('weixin_applet');
        try{
            $path = Wechat::getwxacodeunlimit($wxconf,time(),$scene,'uqrcode/',$url);
        } catch(\Exception $e){
//            echo $e->getMessage();
            $this->result([],-1,$e->getMessage());
        }
        if(!$path){
            $this->result([],-1,'创建二维码失败');
        }
        $update = [
            'sun_image' => $path,
        ];
        $userModel = new User();
        $rs = $userModel->allowField(true)->save($update, ['user_id'=>$userinfo['user_id']]);
        if(!$rs){
            $this->result([],-1,$userModel->getError());
        }
        $this->result([
            'path' => $path
        ],1,'操作成功');
    }

    /**
     * @route('h5/GetNormalQrCode','post')
     * 用户一般分享二维码
     */
    public function GetNormalQrCode() {
        $url = input('post.url');
        $url_data = parse_url($url);
        $get_query = [];
        if(isset($url_data['query'])){
            $query_data = explode('&',$url_data['query']);
            array_walk($query_data,function(&$v){ // 连接参数数组处理
                $data = explode('=',$v);
                $v = $data;
            });
            $key = array_column($query_data,'0');
            $value = array_column($query_data,'1');
            $get_query = array_combine($key,$value); // 键值数组合并
        }
//        var_dump($url_data);
        $userinfo = $this->GetUserInfo();
        $url = parse_url($url)['path'];
//        var_dump($code);die;
        $scene = [
            "from_uid" => $userinfo['user_id'],
        ];
        if(!empty($get_query)){
            $scene = array_merge($get_query,$scene); // 参数数组组合
            array_unique($scene); // 去重
        }
//        var_dump($scene);die;
        $wxconf = config::pull('weixin_applet');
        try{
            $path = Wechat::getwxacodeunlimit($wxconf,time(),$scene,'normalqrcode/',$url);
        } catch(\Exception $e){
//            echo $e->getMessage();
            $this->result([],-1,$e->getMessage());
        }
        if(!$path){
            $this->result([],-1,'创建二维码失败');
        }
        $this->result([
            'path' => $path
        ],1,'操作成功');
    }

    /**
     * @route('h5/ShareNum','get')
     * 获取分享人数列表
     */
    public function ShareNum()
    {
        $userModel = new User();
        $field = "u.nick_name,u.add_time";
        //累计购买金额
        $Allmoney = ",(SELECT SUM(pay_amount) FROM ddt_order WHERE user_id = u.user_id AND pay_status=2 AND order_status between 2 AND 4) as Allmoney";
        //累计购买次数
        $AllNum = ",(SELECT COUNT(*) FROM ddt_order WHERE user_id = u.user_id AND pay_status=2 AND order_status between 2 AND 4) as AllNum";
        $list = $userModel
            ->alias('u')
            ->field($field.$Allmoney.$AllNum)
            ->where(['invite_uid'=>$this->_userid])
            ->order('user_id DESC')
            ->paginate($this->limit);
//		echo $userModel->getLastSql();die;
        $this->result($list,1,'操作成功');
    }

    /**
     * @route('h5/GetUserGrowthLog','get')
     * 获取用户积分列表
     */
    public function GetUserGrowthLog()
    {
        $GrowthLogModel = new GrowthLog();
        $list = $GrowthLogModel->get_growth_record(['user_id'=>$this->_userid],'value_show,note,add_time','add_time DESC',$this->limit);

        $this->result($list,1,'操作成功');
    }

    /**
     * @route('h5/ApplyBeSales','post')
     * 用户申请成为团长
     */
    public function ApplyBeSales()
    {
        $data = input();
        $validate = new ApplyBeSales();
        if(!$validate->scene('apply')->check($data)){
            $this->result([],-1,$validate->getError());
        }

        $applyModel = new ApplySales();
        $apply_log = $applyModel->getOne([['user_id','=',$this->_userid],['status','=',1]]);
        if(!empty($apply_log)){
            $this->result([],-1,'您已申请，请耐心等待审核');
        }
        $orderModel = new OrderModel();
        $order = $orderModel->getOne([['user_id','=',$this->_userid],['pay_status','=',2]]);
        $data['pay_status'] = empty($order)?2:1;
        $data['user_id'] = $this->_userid;
        $data['apply_ip'] = SUtil::getIP();
        $result = $applyModel->edit($data);
        if(!$result){
            $this->result([],-1,$applyModel->getError());
        }

		$userModel = new User();
		$where = ['user_id' => $this->_userid];
		$urs = $userModel->allowField(true)->save(['is_sales' => 2], $where);
		if($urs === false){
			$this->result([],-1,$userModel->getError());
		}

        $this->result([],1,'申请成功');
    }

    /**
     * @route('h5/UserFeedback','post')
     * 用户提交反馈
     */
    public function UserFeedback()
    {
        $data = input();
        if(empty($data['telphone']) || empty($data['content'])){
            $this->result([],-1,'请填写完整反馈信息');
        }

        $feedbackModel = new Feedback();
//        $feedback_log = $feedbackModel->getOne([['user_id','=',$this->_userid]]);
//        if(!empty($feedback_log)){
//            $this->result([],-1,'您已申请，请耐心等待审核');
//        }
        $data['user_id'] = $this->_userid;
        $data['feedback_ip'] = SUtil::getIP();
        $result = $feedbackModel->edit($data);
        if(!$result){
            $this->result([],-1,$feedbackModel->getError());
        }
        $this->result([],1,'反馈成功');
    }

    /**
     * @route('h5/UserGetExam','get')
     * 用户获取问卷
     */
    public function UserGetExam()
    {
        $paperModel = new Exam();
        $data['exam'] = $exam = $paperModel->field('paper_id,paper_title')->where('is_publish','=',1)->find();
        $data['questions'] = [];
        if(!empty($exam)){
            $questionModel = new PaperQuestions();
            $data['questions'] = $questionModel->api_get_list(['paper_id'=>$exam['paper_id']],'','q.question,pq.pq_id,pq.paper_id,pq.ques_id,pq.add_time,q.option');
        }
        $this->result($data,1,'操作成功');
    }

    /**
     * @route('h5/UserAnswerQuestions','post')
     * 用户填写问卷
     */
    public function UserAnswerQuestions()
    {
        $param = input('post.');
        $paperModel = new Exam();
        $exam = $paperModel->getOne(['is_publish' => 1,'paper_id' => $param['paper_id']],'paper_id,paper_title');
        if(empty($exam)){
            $this->result([],-1,'无此问卷');
        }
        $answers = $param['answer'];
        if(!is_array($answers)){
            $json_data = json_decode($answers,true);
            !is_null($json_data)?$answers = $json_data:$this->result([],-1,'提交问卷信息有误');
        }
        if(empty($answers)){
            $this->result([],-1,'请填写问卷再提交');
        }
//        var_dump($answers);die;
        $ques_ids = array_column($answers,'ques_id');
        $paperquestionModel = new PaperQuestions();
        $ques_data = $paperquestionModel->api_get_list(['paper_id'=>$exam['paper_id']],'','pq.ques_id,q.option')->toArray();
        $questions = array_column($ques_data,'ques_id');
//        var_dump($questions);die;
        $diff_one = array_diff($ques_ids,$questions); // 比较返回提交问卷答题不存在的题目信息
        if(count($diff_one) > 0){
            $this->result([],-1,'错误的题目信息');
        }
        $diff_two = array_diff($questions,$ques_ids); // 比较返回提交问卷答题未填写的题目信息
        if(count($diff_two) > 0){
            $this->result([],-1,'请先完成题目作答');
        }
        $now = time();
        array_walk($answers,function(&$v) use($exam,$now){
            $data['user_id'] = $this->_userid;
            $data['at_id'] = $exam['paper_id'];
            $data['ques_id'] = $v['ques_id'];
            $data['ques_title'] = $v['question'];
            $data['answer'] = $v['option'];
            $data['answer_cont'] = $v['option_text'];
            $data['add_time'] = $now;
            $v = $data;
        });
//        var_dump($answers);die;
        $answerModel = new ExamAnswer();
        $rs = $answerModel->saveAll($answers);
        if(!$rs){
            $this->result([],-1,'操作失败');
        }
        $this->result([],1,'操作成功');
    }

    /**
     * @route('h5/TestPushMessage','post')
     * 测试用户消息推送
     */
    public function TestPushMessage()
    {
        $config = config::pull('weixin_applet');
        $messagepush = config::pull('messagepush');
        $userinfo = $this->GetUserInfo();
        $orderModel = new OrderModel();

        $where = [
            ['user_id', '=', $userinfo['user_id']],
            ['order_id', '=',336],
        ];
        $order = $orderModel->getOne($where);
//        var_dump($order);die;
//        $item = 'od.*,s.shop_id';
//        $detail = $orderModel->api_order_details(335, $item);
        $string = '';
//        foreach($detail as $value){
//            !empty($string)? $string .= "，":'';
//            $string .= "{$value['product_name']}({$value['p_s_name']}) X {$value['quantity']}";
//        }
        $cond['order_id'] = 336;
        $field = "a.order_id,a.is_comment,a.address_id,a.receive_name,a.p_c_a,a.r_address,a.r_phone,a.order_status,a.orderno,a.pay_status,a.order_status,a.pay_amount,a.pay_time,b.make_time,b.send_id,b.state,b.service_id,c.service_name,c.top_pic,d.team_name,d.phone";
        $detail = $orderModel->get_Service_Order_list($cond,'',$field);
//        echo $orderModel->getLastSql();
//        var_dump($detail);
        foreach($detail as $value){
//            var_dump($value['service_name']);
            !empty($string)? $string .= "，":'';
            $string .= $value['service_name'];
        }
//        var_dump($string);die;
        $data = [
            'character_string3' => [
                "value" => $order['orderno'],
            ],// 订单编号
            'amount10' => [
                "value" => $order['pay_amount'],
            ],//订单金额
            'thing4' => [
                "value" => $string,
            ],//服务内容
            'thing1' => [
                "value" => $order['p_c_a'].$order['r_address'],
            ],//订单地址
            'phone_number19' => [
                "value" => $order['r_phone'],
            ],//联系电话
        ];
//        var_dump($userinfo);die;
        try{
            $rs = Wechat::messagepush($config,$userinfo['applets_openid'],$messagepush['pushuser'],'',$data);
        }catch (\Exception $e){
            return $e->getMessage();
        }
        return $rs;
    }
}
